/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.institution.controller;

import com.alibaba.fastjson.JSONObject;
import com.koron.common.StaffAttribute;
import com.koron.common.bean.StaffBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.common.web.Util;

import com.koron.institution.bean.Law;

import com.koron.institution.service.api.LawService;
import com.koron.institution.uitls.BusinessCode;
import com.koron.system.annotation.Log;
import com.koron.system.discrete.BusinessManipulation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.ADOConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Api(tags = "law", description = "法规Api类")
@RestController
@RequestMapping(value = "/law")
public class LawController {

    @Autowired
    private LawService lawService;

    @Autowired
    private Util util;

    private static final Logger logger = LoggerFactory.getLogger(LawController.class);

    @ApiOperation("制度列表")
    @RequestMapping(value = "/getAll.htm", method = {RequestMethod.GET})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lawItem", value = "搜索条款", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "page", value = "当前页", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", paramType = "query", dataType = "Integer")})
    public MessageBean<?> getAll(String userCode, String lawItem, Integer page,
                               Integer pageSize, @SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user) {
        if (null == user) {
            List<StaffBean> beanList = (List<StaffBean>) util.staff(userCode, null).getData();
            if (null != beanList && beanList.size() > 0) {
                user = beanList.get(0);
            }
        }
        if (null == user) {
            MessageBean<?> msg = new MessageBean<>();
            msg.setCode(BusinessCode.NOT_LONGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return msg;
        }
        return lawService.getAll(user, lawItem, page, pageSize);
    }

    @ApiOperation("制度列表")
    @RequestMapping(value = "/list.htm", method = {RequestMethod.GET})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileName", value = "文件名称", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "lawItem", value = "法规条款", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "categoryId", value = "目录id", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "page", value = "当前页", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", paramType = "query", dataType = "Integer")})
    public MessageBean<?> list(String userCode,String fileName, String lawItem, String categoryId, Integer page,
                               Integer pageSize, @SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user) {
        if (null == user) {
            List<StaffBean> beanList = (List<StaffBean>) util.staff(userCode, null).getData();
            if (null != beanList && beanList.size() > 0) {
                user = beanList.get(0);
            }
        }
        if (null == user) {
            MessageBean<?> msg = new MessageBean<>();
            msg.setCode(BusinessCode.NOT_LONGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return msg;
        }
        return lawService.getList(user,fileName, lawItem, categoryId, page, pageSize);
    }

    @ApiOperation("法规保存")
    @RequestMapping(value = "/saveOrCommit.htm", method = {RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(value = "法规对象字符串", name = "lawStr", required = true),
            @ApiImplicitParam(value = "文件", name = "file", required = true),
    })
    @Log(title = "法规保存",businessModule = "法规库", businessManipulation = BusinessManipulation.INSERT)
    public MessageBean<?> save(String lawStr, @RequestBody MultipartFile[] file, @SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user) {
        if (null == user) {
            MessageBean<?> msg = new MessageBean<>();
            msg.setCode(BusinessCode.NOT_LONGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return msg;
        }
        return lawService.save(lawStr, user, file);
    }


    @ApiOperation("删除法规")
    @RequestMapping(value = "/discard.htm", method = {RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lawId", value = "法规id", paramType = "query", dataType = "String")
    })
    @Log(title = "删除法规",businessModule = "法规库", businessManipulation = BusinessManipulation.DELETE)
    public MessageBean<?> delete(String lawId, @SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user) {
        if (null == user) {
            MessageBean<?> msg = new MessageBean<>();
            msg.setCode(BusinessCode.NOT_LONGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return msg;
        }
        return lawService.delete(lawId, user);
    }

    @ApiOperation("废弃法规")
    @RequestMapping(value = "/discard1.htm", method = {RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lawId", value = "法规id", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "approverCodeListStr", value = "审批人code集合字符串", required = true, paramType = "query", dataType = "String"),
    })
    @Log(title = "废弃制度删除",businessModule = "法规库", businessManipulation = BusinessManipulation.DELETE)
    public MessageBean<?> discard(String lawId, @SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String approverCodeListStr) {
        if (null == user) {
            MessageBean<?> msg = new MessageBean<>();
            msg.setCode(BusinessCode.NOT_LONGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return msg;
        }
        return lawService.discard(lawId, user, approverCodeListStr);
    }

    @ApiOperation("批量修订法规")
    @RequestMapping(value = "/batchEdit.htm", method = {RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode", value = "水司code", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "historyListStr", value = "修改法规集合字符串", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "approverCodeListStr", value = "审批人code集合字符串", required = true, paramType = "query", dataType = "String"),
    })
    @Log(title = "批量修订法规",businessModule = "法规库", businessManipulation = BusinessManipulation.UPDATE)
    public MessageBean<?> batchEdit(String corpCode, String historyListStr, @RequestBody MultipartFile[] files, @SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user
            , String approverCodeListStr, HttpServletRequest request) {

        MessageBean<?> msg = MessageBean.create(0, "success", Object.class);
        if (null == user) {
            msg.setCode(BusinessCode.NOT_LONGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return msg;
        }
        try {
            List<Law> lawList = JSONObject.parseArray(historyListStr, Law.class);
            if (StringUtils.isBlank(corpCode)) {
                corpCode = user.getCode();
            }
            if (lawList == null || lawList.size() <= 0) {
                msg.setCode(BusinessCode.EDIT_EMPTY_LIST.getCode());
                msg.setDescription(BusinessCode.EDIT_EMPTY_LIST.getDescription());
                return msg;
            }
            MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
            if (DefaultMultipartHttpServletRequest.class.isAssignableFrom(multipartRequest.getClass())) {
                HttpServletRequest otherRequest = ((DefaultMultipartHttpServletRequest) multipartRequest).getRequest();
                if (StandardMultipartHttpServletRequest.class.isAssignableFrom(otherRequest.getClass())) {
                    StandardMultipartHttpServletRequest standardMultipartHttpServletRequest = (StandardMultipartHttpServletRequest) otherRequest;
                    for (int i = 0; i < lawList.size(); i++) {
                        Law law = lawList.get(i);
                        law.setFiles(standardMultipartHttpServletRequest.getFiles("files" + i));
                    }
                }
            }
            msg = lawService.batchEdit(corpCode, lawList, user, approverCodeListStr);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
        return msg;
    }

    @ApiOperation("法规历史版本列表")
    @RequestMapping(value = "/historyList.htm", method = {RequestMethod.GET})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileName", value = "文件名称", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "corpCode", value = "公司code", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "version", value = "版本号", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "page", value = "当前页", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", paramType = "query", dataType = "Integer")
    })
    public MessageBean<?> historyList(String fileName, String corpCode,
                                      String version, Integer page, Integer pageSize, @SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user) {
        return lawService.getHistoryList(fileName, corpCode, version, page, pageSize);
    }


    @ApiOperation("通过制度编号获取制度历史版本列表")
    @RequestMapping(value = "/historyListByCode.htm", method = {RequestMethod.GET})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "制度编号", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "page", value = "当前页", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", paramType = "query", dataType = "Integer")
    })
    public MessageBean<?> historyListByCode(String code, Integer page, Integer pageSize, @SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user) {
        return lawService.getHistoryListByCode(code, page, pageSize);
    }

    @ApiOperation("保存文件")
    @RequestMapping(value = "/saveFile.htm", method = {RequestMethod.POST})
    public MessageBean<?> saveFile(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestBody MultipartFile[] files) {
        return lawService.saveFile(files);
    }


    @ApiOperation("法规文件导入")
    @RequestMapping(value = "/importFile.htm", method = {RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "categoryId", value = "目录id", paramType = "query", dataType = "String"),
    })
    public MessageBean<?> saveFile(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String userCode, String categoryId, @RequestBody MultipartFile[] files) {
        if (null == user) {
            List<StaffBean> beanList = (List<StaffBean>) util.staff(userCode, null).getData();
            if (null != beanList && beanList.size() > 0) {
                user = beanList.get(0);
            }
        }
        return lawService.importFile(categoryId, user, files);
    }

    @ApiOperation("法规条款导入")
    @RequestMapping(value = "/importLawItem.htm", method = {RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lawId", value = "法规id", required = true, paramType = "query", dataType = "String"),
    })
    public MessageBean<?> importLawItem(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String userCode, String lawId, @RequestBody MultipartFile file) {
        if (null == user) {
            List<StaffBean> beanList = (List<StaffBean>) util.staff(userCode, null).getData();
            if (null != beanList && beanList.size() > 0) {
                user = beanList.get(0);
            }
        }
        return lawService.importLawItem(lawId, user, file);
    }

    @ApiOperation("法规条款模糊搜索")
    @RequestMapping(value = "/getLawItems.htm", method = {RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileName", value = "法规文件名", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "lawItem", value = "法规条款", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "page", value = "当前页", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", paramType = "query", dataType = "int"),
    })
    public MessageBean<?> getLawItems(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = false) String userCode, @RequestParam(required = false)String fileName,
                                      @RequestParam(required = false)String lawItem, @RequestParam(required = false)Integer page, @RequestParam(required = false)Integer pageSize) {
        if (null == user) {
            MessageBean<?> msg = new MessageBean<>();
            msg.setCode(BusinessCode.NOT_LONGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return msg;
        }
        return ADOConnection.runTask(factory -> lawService.getLawItems(factory,fileName,lawItem,page,pageSize),MessageBean.class);
    }

    @ApiOperation("删除文件")
    @RequestMapping(value = "/deleteFile.htm", method = {RequestMethod.POST})
    public MessageBean<?> deleteFile(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String filePaths) {
        return lawService.deleteFile(filePaths);
    }

    @ApiOperation("流程中的业务数据")
    @ApiImplicitParam(name = "ids", value = "流程关联的业务ids", required = true, paramType = "query", dataType = "String")
    @RequestMapping(value = "/getProcessData.htm", method = {RequestMethod.GET})
    public MessageBean<?> getProcessData(String ids) {
        return lawService.getProcessData(ids);
    }
}
